﻿using System.Collections.Generic;
using System.Linq;
using compshop.Modules.PositionList.View;
using compshop.Infrastructure;
using compshop.Infrastructure.CompShopDataService;

namespace compshop.Modules.PositionList.Presenter
{
    public class PositionListPresenter
    {
        private CompShopEntities contextDS;
        private EventsManager eventsManager;
        private IList<Position> _positions;

        public IViewPositionList View { set; get; }

        public PositionListPresenter(EventsManager eventsManager)
        {
            contextDS = CompShopEntitiesContext.GetInstance();
            this.eventsManager = eventsManager;
            eventsManager.positionListPresenter = this;
            _positions = GetPositions();
        }

        public IList<Position> Positions 
        {
            set { _positions = value; }
            get { return _positions; }
        }

        public IList<Position> GetPositions()
        {
                var query =
                        from p in contextDS.Positions
                        select p;

                return query.ToList<Position>();
        }

        public void ShowPositionDialog(Position position)
        {
            PositionDialog dialog = new PositionDialog(position);
            if (dialog.ShowDialog() == true)
            {
                try
                {
                    if (dialog.Position.PositionID == 0)
                    {
                        contextDS.AddToPositions(dialog.Position);
                        Positions.Add(dialog.Position);
                    }

                    else
                        contextDS.UpdateObject(dialog.Position);

                    contextDS.SaveChanges();
                }
                catch (System.Exception ex)
                {
                    System.Windows.MessageBox.Show(Resource.msgSaveToDBError + "\n" + ex.Message);
                }

                View.UpdateData();
            }
        }


        #region Publishers
        public void onSelectedPosition(int id)
        {
            eventsManager.EventAggregator.GetEvent<PositionSelectedEvent>().Publish(id);
        }
        #endregion

        #region Handlers
        public void SetSelectedPosition(int id)
        {

        }
        #endregion

    }
}
